package com.hyf.okhttp3demo.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.hyf.okhttp3demo.Config;
import com.hyf.okhttp3demo.R;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class GetRequestActivity extends AppCompatActivity {

    private Button mButton;
    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_request);
        mButton = (Button) findViewById(R.id.btn_get);
        mTextView = (TextView) findViewById(R.id.tv_show);

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OkHttpClient client = new OkHttpClient();
                final Request request = new Request.Builder().url(Config.API.URL_GET).get().build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("GetRequestActivity", e.getLocalizedMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String result = response.body().string();
                        Log.e("GetRequestActivity", result);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mTextView.setText(result);
                            }
                        });
                    }
                });
            }
        });
    }
}
